using Microsoft.AspNetCore.Mvc;
using System.Text.Json;
using Microsoft.AspNetCore.Http;

namespace MVCWeekOne.Controllers
{
    /// <summary>
    /// 报工页面控制器（调用 Read API）
    /// </summary>
    public class WorkReportController : Controller
    {
        private readonly IConfiguration _configuration;
        private readonly HttpClient _httpClient;
        private readonly string _readApiUrl;

        public WorkReportController(IConfiguration configuration, HttpClient httpClient)
        {
            _configuration = configuration;
            _httpClient = httpClient;
            _readApiUrl = _configuration["ApiSettings:ReadApiUrl"] ?? "http://localhost:5089/api";
        }

        /// <summary>
        /// 报工页面
        /// </summary>
        [HttpGet]
        public IActionResult Index()
        {
            ViewData["WriteApiUrl"] = _configuration["ApiSettings:WriteApiUrl"] ?? "http://localhost:5090/api";
            ViewBag.ReadApiUrl = _readApiUrl;
            return View();
        }

        /// <summary>
        /// 报工分页查询（透传至 Read API）
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> SearchWorkReport(
            string? workOrderCode,
            string? processName,
            string? productCode,
            string? processStatus,
            DateTime? createTimeStart,
            DateTime? createTimeEnd,
            string sortField = "Id",
            string sortDirection = "desc",
            int pageIndex = 1,
            int pageSize = 30)
        {
            var queryParams = new List<string>();
            if (!string.IsNullOrWhiteSpace(workOrderCode)) queryParams.Add($"WorkOrderCode={Uri.EscapeDataString(workOrderCode)}");
            if (!string.IsNullOrWhiteSpace(processName)) queryParams.Add($"ProcessName={Uri.EscapeDataString(processName)}");
            if (!string.IsNullOrWhiteSpace(productCode)) queryParams.Add($"ProductCode={Uri.EscapeDataString(productCode)}");
            if (!string.IsNullOrWhiteSpace(processStatus)) queryParams.Add($"ProcessStatus={Uri.EscapeDataString(processStatus)}");
            if (createTimeStart.HasValue) queryParams.Add($"CreateTimeStart={createTimeStart:O}");
            if (createTimeEnd.HasValue) queryParams.Add($"CreateTimeEnd={createTimeEnd:O}");

            queryParams.Add($"SortField={Uri.EscapeDataString(sortField)}");
            queryParams.Add($"SortDirection={Uri.EscapeDataString(sortDirection)}");
            queryParams.Add($"PageIndex={pageIndex}");
            queryParams.Add($"PageSize={pageSize}");

            var url = $"{_readApiUrl}/WorkReport/SearchWorkReport?{string.Join("&", queryParams)}";

            try
            {
                var resp = await _httpClient.GetAsync(url);
                var content = await resp.Content.ReadAsStringAsync();
                if (resp.IsSuccessStatusCode)
                {
                    return Content(content, "application/json");
                }
                return Json(new { code = (int)resp.StatusCode, msg = "请求失败", data = new { } });
            }
            catch (Exception ex)
            {
                return Json(new { code = 500, msg = $"异常: {ex.Message}", data = new { } });
            }
        }

        /// <summary>
        /// 获取所有满足条件的报工 Id（大分页）
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetAllWorkReportIds(
            string? workOrderCode,
            string? processName,
            string? productCode,
            string? processStatus,
            DateTime? createTimeStart,
            DateTime? createTimeEnd)
        {
            const int MaxSize = 1_000_000;
            var queryParams = new List<string>();
            if (!string.IsNullOrWhiteSpace(workOrderCode)) queryParams.Add($"WorkOrderCode={Uri.EscapeDataString(workOrderCode)}");
            if (!string.IsNullOrWhiteSpace(processName)) queryParams.Add($"ProcessName={Uri.EscapeDataString(processName)}");
            if (!string.IsNullOrWhiteSpace(productCode)) queryParams.Add($"ProductCode={Uri.EscapeDataString(productCode)}");
            if (!string.IsNullOrWhiteSpace(processStatus)) queryParams.Add($"ProcessStatus={Uri.EscapeDataString(processStatus)}");
            if (createTimeStart.HasValue) queryParams.Add($"CreateTimeStart={createTimeStart:O}");
            if (createTimeEnd.HasValue) queryParams.Add($"CreateTimeEnd={createTimeEnd:O}");

            queryParams.Add("PageIndex=1");
            queryParams.Add($"PageSize={MaxSize}");
            queryParams.Add("SortField=Id");
            queryParams.Add("SortDirection=desc");

            var url = $"{_readApiUrl}/WorkReport/SearchWorkReport?{string.Join("&", queryParams)}";

            try
            {
                var resp = await _httpClient.GetAsync(url);
                if (!resp.IsSuccessStatusCode) return Json(new { code = (int)resp.StatusCode, msg = "读取失败", data = new List<int>() });

                var content = await resp.Content.ReadAsStringAsync();
                using var doc = JsonDocument.Parse(content);
                var ids = doc.RootElement.GetProperty("data").GetProperty("data").EnumerateArray()
                    .Select(e => e.GetProperty("id").GetInt32()).ToList();
                return Json(new { code = 200, msg = "OK", data = ids });
            }
            catch (Exception ex)
            {
                return Json(new { code = 500, msg = $"异常: {ex.Message}", data = new List<int>() });
            }
        }
    }
} 